///新版本 我的
import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_ahj_app/TestViewModel.dart';
import 'package:flutter_ahj_app/app/my/view/subViews/UserInfo.dart';
import 'package:flutter_ahj_app/app/NewMine/MyViewModel.dart';
import 'package:flutter_ahj_app/base/cunchu/Constant.dart';
import 'package:flutter_ahj_app/base/cunchu/UserInfoUtils.dart';
import 'package:flutter_ahj_app/base/rouleutils/RouleUtils.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/ShowFiles/GetFilesPath.dart';
import 'package:flutter_ahj_app/base/utils/ShowFiles/GetImageWidget.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/eventBus.dart';
import 'package:flutter_ahj_app/base/utils/font_utils.dart';
import 'package:flutter_ahj_app/base/utils/screen_util.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';

import '../../../base/basewidget/view/BaseWidget.dart';

const double space = 15;

class LoginAtOnceView extends BaseStatefulWidget {
  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    return LoginAtOnceViewState();
  }
}

class LoginAtOnceViewState extends BaseState<TestViewModel, LoginAtOnceView> {
  TextEditingController _nameContro = new TextEditingController(text: '');

  String showMiMa = "1";
  String loginType = "0"; //0：账号密码登录 1：验证码登录
  String pwd = "";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }

  @override
  Widget initWidget() {
    // TODO: implement initWidget
    return Container(
      // color: Color(0xFFF2F2F2),
      child: Stack(
        children: [
          Container(
            child: Image.asset('img/login_nosy_bg.png', fit: BoxFit.cover,
              width: ScreenUtil.getScreenW(context), height: ScreenUtil.getScreenH(context),),
          ),
          _topView(),
          Scaffold(
            backgroundColor: Color(0x00ffffff),
            body: _bodyView(),
          ),
          Positioned(child:  _userAgreexy(), bottom: 20, left: 0,right: 0,),
        ],
      ),
    );
  }
  _bodyView() {
    return SingleChildScrollView(
      child: Container(
        margin: EdgeInsets.only(top: 265),
        height: ScreenUtil.getScreenH(context) - 265,
        decoration: BoxDecoration(
          borderRadius: new BorderRadius.all(Radius.circular(16.0)),
          gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [SQColor.white, Color(0xffF4F5F7)]),),
        child: Column(
          children: [
            _loginView(),
            _loginBtnContent(),
            _loginTypeView(),
          ],
        ),
      ),
    );
  }


  _topView() {
    return Container(alignment: Alignment.center,margin: EdgeInsets.only(top: 135),child:
      Column(crossAxisAlignment: CrossAxisAlignment.center,children: [
        Image.asset(
          'img/login_logo.png',
          height: Dimens.dimens80,
          width: Dimens.dimens80,
          fit: BoxFit.cover,
        ),
        SizedBox(height: Dimens.dimens12,),
        Container(padding: EdgeInsets.only(left: Dimens.dimens12),child:
        JText('15838209599', color: SQColor.black_333333, fontSize: 18, fontWeight: FontWeight.w500,)),
    ],),);
  }

  _loginTypeView() {
     return Container(margin: EdgeInsets.fromLTRB(30, 26, 30, 0), child:
     Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
       children: <Widget>[
        InkWell(child:  Container(alignment: Alignment.center,
          child: Text(
             "密码登录",
            style:
            new TextStyle(color: Color(0xFF3264F5), fontSize: 13, fontWeight: FontWeight.w400),
          ),
        ),onTap: () {
          setState(() {
            if (loginType == "0"){
              loginType = "1";
            } else {
              loginType = "0";
            }

          });
        },),
         Container(height: 18, width: 1,color: SQColor.lineE7E7E7,),
         InkWell(
           child: Container(
             child: Text(
              "短信验证码登录",
               style:
               new TextStyle(color: Color(0xFF3264F5), fontSize: 13, fontWeight: FontWeight.w400),
             ),
           ),
           onTap: () {

           },
         ),
       ],
     ),);
  }

  _loginView() {
    return loginType == "0" ? _umLoginView() : _ucLoginView();
  }

  _umLoginView() {
    TextField name = new TextField(
        autofocus: true,
        decoration: new InputDecoration(
          labelText: "手机号",
          labelStyle: new TextStyle(color: SQColor.black_333333, fontSize: 16, fontWeight: FontWeight.w500),
          hintText: "请输入您的手机号",
          hintStyle: new TextStyle(color: Color(0xffbfbfbf), fontSize: 14, fontWeight: FontWeight.w400),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(
              color: SQColor.lineE7E7E7, //边线颜色为黄色
              width: 1, //边线宽度为2
            ),
          ),
          focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(
                color: SQColor.lineE7E7E7, //边框颜色为绿色
                width: 1, //宽度为5
              )),
        ),
        controller: _nameContro,
        style: new TextStyle(color: SQColor.black_333333),
        cursorColor: SQColor.black_333333,
        inputFormatters: [
          LengthLimitingTextInputFormatter(11),
          // WhitelistingTextInputFormatter(RegExp("[0-9]")),
        ]);
    TextField password = new TextField(
      inputFormatters: [
        // WhitelistingTextInputFormatter(RegExp("[0-9]|[a-z]|[A-Z]")),
      ],
      decoration: InputDecoration(
        labelText: "密码",
        labelStyle: new TextStyle(color: SQColor.black_333333, fontSize: 16, fontWeight: FontWeight.w500),
        hintText: "请输入密码",
        hintStyle: new TextStyle(color: Color(0xffbfbfbf), fontSize: 14, fontWeight: FontWeight.w400),
        suffixIcon: new IconButton(
            icon: Icon(
              showMiMa == "1" ? Icons.visibility_off : Icons.visibility,
              color: SQColor.lineE7E7E7,
            ),
            onPressed: isShowMiMa),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: SQColor.lineE7E7E7, //边线颜色为黄色
            width: 1, //边线宽度为2
          ),
        ),
        focusedBorder: UnderlineInputBorder(
            borderSide: BorderSide(
              color:SQColor.lineE7E7E7, //边框颜色为绿色
              width: 1, //宽度为5
            )),
      ),
      obscureText: showMiMa == "1" ? true : false,
      controller: TextEditingController.fromValue(
        TextEditingValue(
            text: pwd,
            selection: TextSelection.fromPosition(TextPosition(
                affinity: TextAffinity.downstream, offset: pwd.length))),
      ),
      style: new TextStyle(color: SQColor.black_333333),
      cursorColor: SQColor.black_333333,
      onChanged: (String str) {
        setState(() {
          pwd = str;
        });
      },
    );
    return Container(margin: EdgeInsets.only(left: Dimens.dimens26, right: Dimens.dimens26, top: Dimens.dimens20),child:
    Column(
      children: <Widget>[
        name,
        SizedBox(height: Dimens.dimens18,),
        password,
      ],
    ),);
  }

  TextEditingController _phoneController = new TextEditingController(text: ''),
      _checkController = new TextEditingController(text: '');
  String _checkText = "获取验证码";
  Timer countDownTimer; //获取验证码计时器
  _ucLoginView() {
    TextField _tfPhone = TextField(
        decoration: InputDecoration(
          labelText: "手机号",
          labelStyle: new TextStyle(color: SQColor.black_333333, fontSize: 16, fontWeight: FontWeight.w500),
          hintText: "请输入您的手机号",
          hintStyle: new TextStyle(color: Color(0xffbfbfbf), fontSize: 14, fontWeight: FontWeight.w400),
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(
              color: SQColor.lineE7E7E7, //边线颜色为黄色
              width: 1, //边线宽度为2
            ),
          ),
          focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(
                color: SQColor.lineE7E7E7, //边框颜色为绿色
                width: 1, //宽度为5
              )),
        ),
        controller: _phoneController,
        style: TextStyle(color: SQColor.black_333333),
        cursorColor: SQColor.black_333333,
        keyboardType: TextInputType.phone,
        inputFormatters: [
          LengthLimitingTextInputFormatter(11),
          FilteringTextInputFormatter.allow(RegExp("[0-9]")),
        ]);
    GestureDetector _rbGetCheck = GestureDetector(
      child: new Container(
        alignment: Alignment.center,
        height: Dimens.dimens36,
        width: Dimens.dimens96,
        child: Text(
          _checkText,
          style: new TextStyle(
              fontSize: Dimens.textSize28,
              color:
              _checkText == "获取验证码" ? SQColor.black_333333 : SQColor.per60Black),
        ),
      ),
      onTap: _checkText == "获取验证码" ? () => _getCheckCode() : null,
    );

    TextField _tfCheck = TextField(
        decoration: InputDecoration(
          labelText: "验证码",
          labelStyle: new TextStyle(color: SQColor.black_333333, fontSize: 16, fontWeight: FontWeight.w500),
          hintText: "请输入验证码",
          hintStyle: new TextStyle(color: Color(0xffbfbfbf), fontSize: 14, fontWeight: FontWeight.w400),
          suffixIcon: _rbGetCheck,
          enabledBorder: UnderlineInputBorder(
            borderSide: BorderSide(
              color: SQColor.lineE7E7E7, //边线颜色为黄色
              width: 1, //边线宽度为2
            ),
          ),
          focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(
                color: SQColor.lineE7E7E7, //边框颜色为绿色
                width: 1, //宽度为5
              )),
        ),
        controller: _checkController,
        style: TextStyle(color: SQColor.black_333333),
        cursorColor: SQColor.black_333333,
        keyboardType: TextInputType.phone,
        inputFormatters: [
          LengthLimitingTextInputFormatter(6),
          FilteringTextInputFormatter.allow(RegExp("[0-9]")),
        ]);
    return  Container( padding: EdgeInsets.fromLTRB(26, 20, 26, 0),child: Column(
      children: <Widget>[
        _tfPhone,
        SizedBox(height: Dimens.dimens18,),
        _tfCheck,
      ],
    ),);
  }


  _getCheckCode() async {
    RegExp exp = RegExp('^^(1[3-9])\\d{9}\$');
    if (_phoneController.text == null || _phoneController.text.trim() == "") {
      ToastUtils.showToast("请输入手机号");
      return;
    }
    bool matched = exp.hasMatch(_phoneController.text);
    if (!matched) {
      ToastUtils.showToast("请输入正确格式的手机号");
      return;
    }
    final connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.none) {
      ToastUtils.showToast("请检查手机网络设置");
      return;
    }

    countDownTimer?.cancel(); //如果已存在先取消置空
    countDownTimer = null;
    setState(() {
      _checkText = "60秒";
    });
    countDownTimer = new Timer.periodic(new Duration(seconds: 1), (t) {
      setState(() {
        if (60 - t.tick > 0) {
          //60-t.tick代表剩余秒数，如果大于0，设置yzmText为剩余秒数，否则重置yzmText，关闭countTimer
          _checkText = "${60 - t.tick}秒";
        } else {
          _checkText = '获取验证码';
          countDownTimer.cancel();
          countDownTimer = null;
        }
      });
    });
  }

  void isShowMiMa() {
    setState(() {
      showMiMa == "1" ? showMiMa = "0" : showMiMa = "1";
    });
  }

  _loginBtnContent () {
    return  InkWell(child: Container(
      margin: EdgeInsets.fromLTRB(27, 35, 27, 0),
      decoration: BoxDecoration(
        color: SQColor.theme_color,
        borderRadius: BorderRadius.all(Radius.circular(24.0)),
      ),
      child: Center(child:
      Row(mainAxisAlignment: MainAxisAlignment.center,children: [
        JText('登录', color: SQColor.white, fontSize: 16, fontWeight: FontWeight.w500,)],),),
      height: 48,), onTap: () {

    },);
  }

  bool _isCheckXY = false;
  _userAgreexy() {
    return Container(alignment: Alignment.center,padding: EdgeInsets.only(bottom: 20),child: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        InkWell(
          onTap: () {
            setState(() {
              _isCheckXY = !_isCheckXY;
            });
          },
          child: Image.asset(
            _isCheckXY ? "img/xieyi_xz.png" : "img/xieyi_wxz.png",
            width: Dimens.dimens20,
            height: Dimens.dimens20,
          ),
        ),
        RichText(
          maxLines: 2,
          text: TextSpan(
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                setState(() {
                  _isCheckXY = !_isCheckXY;
                });
              },
            text: '  本人已阅读、知晓并同意',
            style: TextStyle(
              color: SQColor.black_999999,
              fontSize: Dimens.dimens12,
            ),
            children: <TextSpan>[
              TextSpan(
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    Navigator.pushNamed(context, "/PTXYView",
                        arguments: '1');
                  },
                text: '《用户隐私协议》',
                style: TextStyle(
                    color: SQColor.black_333333,
                    fontSize: Dimens.dimens12,
                    fontWeight: FontWeight.bold),
              ),
              // TextSpan(
              //   text: '和',
              //   style: TextStyle(
              //       color: SQColor.white,
              //       fontSize: Dimens.dimens14),
              // ),
              // TextSpan(
              //   text: '《自雇者承揽协议》',
              //   recognizer: TapGestureRecognizer()
              //     ..onTap = () {
              //       Navigator.pushNamed(context, "/PTXYView",
              //           arguments: '2');
              //     },
              //   style: TextStyle(
              //       color: SQColor.secondary1,
              //       fontSize: Dimens.dimens14,
              //       fontWeight: FontWeight.bold),
              // ),
            ],
          ),
        )
      ],
    ),);
  }

  @override
  void dispose() {
    super.dispose();
    countDownTimer?.cancel();
    countDownTimer = null;
  }

}
